"""
AI智能体数据模型
"""

from datetime import datetime
from enum import Enum
from typing import List, Optional, Dict, Any, Union

from pydantic import BaseModel, Field, field_validator, ConfigDict, model_serializer


class AgentStatus(int, Enum):
    """智能体状态枚举（保留用于兼容性）"""
    DISABLED = 0  # 停用
    ENABLED = 1  # 启用
    TRAINING = 2  # 训练中

    @classmethod
    def validate_status(cls, value):
        """验证并转换status值"""
        if isinstance(value, int):
            if value in [0, 1, 2]:
                return value
            else:
                raise ValueError(f"无效的状态值: {value}，必须是 0, 1, 2 中的一个")
        elif isinstance(value, str):
            try:
                int_value = int(value)
                if int_value in [0, 1, 2]:
                    return int_value
                else:
                    raise ValueError(f"无效的状态值: {value}，必须是 0, 1, 2 中的一个")
            except ValueError:
                raise ValueError(f"无效的状态值: {value}，必须是 0, 1, 2 中的一个")
        else:
            raise ValueError(f"状态值必须是整数，当前类型: {type(value)}")


class AIWebAgent(BaseModel):
    """AI智能体实体类"""
    agent_id: str = Field(..., description="智能体唯一标识，UUID")
    scene_id: str = Field(..., description="所属场景ID")
    tenant_id: str = Field(default="default", description="租户ID")
    agent_code: str = Field(..., description="智能体核心逻辑代码")
    agent_name: str = Field(default="", max_length=100, description="智能体名称")
    sys_prompt: str = Field(..., description="系统提示词")
    llm_code: str = Field(..., max_length=255, description="大模型代码，如gpt-4-turbo")
    embedding_code: str = Field(..., max_length=255, description="向量模型代码，如text-embedding-3-large")
    tools_list: List[Union[str, Dict[str, Any]]] = Field(default_factory=list, description="工具配置列表")
    mcp_list: List[Union[str, Dict[str, Any]]] = Field(default_factory=list, description="MCP工具配置列表")
    rag_list: List[Dict[str, Any]] = Field(default_factory=list, description="检索增强配置")
    status: int = Field(default=0, description="状态：0-停用，1-启用，2-训练中")
    version: str = Field(default="1.0.0", max_length=20, description="版本号")
    is_deleted: int = Field(default=0, description="删除标记：0-未删除,1-已删除")
    created_by: str = Field(..., max_length=50, description="创建者")
    created_at: datetime = Field(..., description="创建时间")
    updated_by: Optional[str] = Field(None, max_length=50, description="更新者")
    updated_at: Optional[datetime] = Field(None, description="更新时间")

    model_config = ConfigDict(from_attributes=True)

    @model_serializer
    def serialize_model(self):
        """自定义序列化器"""
        data = self.__dict__.copy()
        if 'created_at' in data and data['created_at']:
            data['created_at'] = data['created_at'].isoformat()
        if 'updated_at' in data and data['updated_at']:
            data['updated_at'] = data['updated_at'].isoformat()
        return data

    @field_validator('version')
    @classmethod
    def validate_version(cls, v):
        """验证版本号格式"""
        import re
        if not re.match(r'^[0-9]+(\.[0-9]+)*$', v):
            raise ValueError('版本号格式不正确，应为数字和点的组合，如1.0.0')
        return v

    @field_validator('is_deleted')
    @classmethod
    def validate_is_deleted(cls, v):
        """验证删除标记"""
        if v not in [0, 1]:
            raise ValueError('删除标记只能是0或1')
        return v

    @field_validator('status', mode='before')
    @classmethod
    def validate_status_field(cls, v):
        """验证status字段"""
        return AgentStatus.validate_status(v)


class AIWebAgentCreate(BaseModel):
    """创建智能体请求模型"""
    scene_id: str = Field(..., description="所属场景ID")
    tenant_id: str = Field(default="default", description="租户ID")
    agent_code: str = Field(..., description="智能体核心逻辑代码")
    agent_name: str = Field(default="", max_length=100, description="智能体名称")
    sys_prompt: str = Field(..., description="系统提示词")
    llm_code: str = Field(..., max_length=255, description="大模型代码，如gpt-4-turbo")
    embedding_code: str = Field(..., max_length=255, description="向量模型代码，如text-embedding-3-large")
    tools_list: List[Union[str, Dict[str, Any]]] = Field(default_factory=list, description="工具配置列表")
    mcp_list: List[Union[str, Dict[str, Any]]] = Field(default_factory=list, description="MCP工具配置列表")
    rag_list: List[Dict[str, Any]] = Field(default_factory=list, description="检索增强配置")
    status: int = Field(default=0, description="状态：0-停用，1-启用，2-训练中")
    version: str = Field(default="1.0.0", max_length=20, description="版本号")
    created_by: str = Field(..., max_length=50, description="创建者")

    @field_validator('version')
    @classmethod
    def validate_version(cls, v):
        """验证版本号格式"""
        import re
        if not re.match(r'^[0-9]+(\.[0-9]+)*$', v):
            raise ValueError('版本号格式不正确，应为数字和点的组合，如1.0.0')
        return v

    @field_validator('status', mode='before')
    @classmethod
    def validate_status_field(cls, v):
        """验证status字段"""
        return AgentStatus.validate_status(v)


class AIWebAgentUpdate(BaseModel):
    """更新智能体请求模型"""
    agent_code: Optional[str] = Field(None, description="智能体核心逻辑代码")
    agent_name: Optional[str] = Field(None, max_length=100, description="智能体名称")
    sys_prompt: Optional[str] = Field(None, description="系统提示词")
    llm_code: Optional[str] = Field(None, max_length=255, description="大模型代码，如gpt-4-turbo")
    embedding_code: Optional[str] = Field(None, max_length=255, description="向量模型代码，如text-embedding-3-large")
    tools_list: Optional[List[Union[str, Dict[str, Any]]]] = Field(None, description="工具配置列表")
    mcp_list: Optional[List[Union[str, Dict[str, Any]]]] = Field(None, description="MCP工具配置列表")
    rag_list: Optional[List[Dict[str, Any]]] = Field(None, description="检索增强配置")
    status: Optional[int] = Field(None, description="状态：0-停用，1-启用，2-训练中")
    version: Optional[str] = Field(None, max_length=20, description="版本号")
    updated_by: str = Field(..., max_length=50, description="更新者")

    @field_validator('version')
    @classmethod
    def validate_version(cls, v):
        """验证版本号格式"""
        if v is not None:
            import re
            if not re.match(r'^[0-9]+(\.[0-9]+)*$', v):
                raise ValueError('版本号格式不正确，应为数字和点的组合，如1.0.0')
        return v

    @field_validator('status', mode='before')
    @classmethod
    def validate_status_field(cls, v):
        """验证status字段"""
        if v is not None:
            return AgentStatus.validate_status(v)
        return v


class AIWebAgentResponse(BaseModel):
    """智能体响应模型"""
    agent_id: str
    scene_id: str
    tenant_id: str
    agent_code: str
    agent_name: str
    sys_prompt: str
    llm_code: str
    embedding_code: str
    tools_list: List[Union[str, Dict[str, Any]]]
    mcp_list: List[Union[str, Dict[str, Any]]]
    rag_list: List[Dict[str, Any]]
    status: int
    version: str
    is_deleted: int
    created_by: str
    created_at: datetime
    updated_by: Optional[str]
    updated_at: Optional[datetime]

    model_config = ConfigDict(from_attributes=True)


class AIWebAgentQueryParams(BaseModel):
    """智能体查询参数"""
    scene_id: Optional[str] = Field(None, description="所属场景ID")
    tenant_id: Optional[str] = Field(None, description="租户ID")
    agent_name: Optional[str] = Field(None, description="智能体名称模糊查询")
    status: Optional[int] = Field(None, description="状态筛选")
    llm_code: Optional[str] = Field(None, description="大模型代码筛选")
    created_by: Optional[str] = Field(None, description="创建者筛选")
    is_deleted: int = Field(default=0, description="删除标记：0-未删除,1-已删除")


class AIWebAgentListResponse(BaseModel):
    """智能体列表响应模型"""
    total: int = Field(..., description="总数量")
    items: List[AIWebAgentResponse] = Field(..., description="智能体列表")


class AIWebAgentStatusUpdate(BaseModel):
    """智能体状态更新模型"""
    status: int = Field(..., description="新状态")
    updated_by: str = Field(..., max_length=50, description="更新者")

    @field_validator('status', mode='before')
    @classmethod
    def validate_status_field(cls, v):
        """验证status字段"""
        return AgentStatus.validate_status(v)


class AIWebAgentVersionUpdate(BaseModel):
    """智能体版本更新模型"""
    version: str = Field(..., max_length=20, description="新版本号")
    updated_by: str = Field(..., max_length=50, description="更新者")

    @field_validator('version')
    @classmethod
    def validate_version(cls, v):
        """验证版本号格式"""
        import re
        if not re.match(r'^[0-9]+(\.[0-9]+)*$', v):
            raise ValueError('版本号格式不正确，应为数字和点的组合，如1.0.0')
        return v
